package com.lishe.lishe.lishe.http;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.util.Log;

import com.lishe.lishe.lishe.base.BaseApplication;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.utils.PermissionUtils;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 分段下载
 * 文件下载类
 * Created by 伟 on 2017/2/20.
 */

public class HttpLoadFile {
    private int cunont;
    private int cunont0 = 0;
    ExecutorService cachedThreadPool;
    private int loadSize;//已下载的文件大小
    private int fileSize;//文件大小

    public void down(Context context,String fileUrl, String fileName, int threadCuont) throws Exception {
        if (threadCuont < 0) {//确保线程数不小于0
            threadCuont = 1;
        }
        fileName="my_download_jpg.jpg";
        fileUrl="https://timgsa.baidu.com/timg?image&quality=80&size=b10000_10000&sec=1504604310&di=fafc294b2a6fa25828495b289a9165fd&src=http%3A%2F%2Fd.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F738b4710b912c8fcc8da787eff039245d6882153.jpg";
        cunont = threadCuont;
        cunont0 = 0;
        loadSize = 0;
        fileName = getSDPath(context) + "/" + fileName;
        URL url = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(60000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Connection", "Keep-Alive");
        int code = conn.getResponseCode();
        if (code == 200) {
            fileSize = conn.getContentLength();//获取下载文件的大小
            //计算每条线程点的下载文件大小
            int size = fileSize / threadCuont;
            RandomAccessFile raFile = new RandomAccessFile(fileName, "rwd");//创建文件
            raFile.setLength(fileSize);//设置文件大小
            raFile.close();
            Log.e("文件大小"+size,"--"+fileSize);
            //创建线程池
            cachedThreadPool = Executors.newCachedThreadPool();
            for (int threadId = 1; threadId <= threadCuont; threadId++) {//创建线程
                int starPosition = (threadId - 1) * size;//开始位置
                int endPosition = threadId * size - 1;//结束位置
                if (threadId == threadCuont) {//最后一个线程
                    endPosition = fileSize;
                }
                MyRun run = new MyRun(threadId, fileUrl, fileName, starPosition, endPosition);
                cachedThreadPool.execute(run);
            }
        } else {
            if(listener!=null){
                listener.erro(code);
                listener.sucee(false, fileName);
            }
        }
    }

    class MyRun implements Runnable {
        String fileUrl;
        String fileName;
        int starPotion;
        int endPotion;
        int threadId;

        MyRun(int threadId, String fileUrl, String fileName, int starPotion, int endPotion) {
            this.fileUrl = fileUrl;
            this.starPotion = starPotion;
            this.endPotion = endPotion;
            this.threadId = threadId;
            this.fileName = fileName;
        }

        @Override
        public void run() {
            try {
                URL url = new URL(fileUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Range", "bytes=" + starPotion + "-" + endPotion);//如果不写这句，则会每一条线程都会把文件完整下载一遍，并且返回值是206
                conn.setConnectTimeout(60000);
                int code = conn.getResponseCode();
                if (code == 200 || code == 206) {
                    InputStream is = conn.getInputStream();
                    RandomAccessFile raFile = new RandomAccessFile(fileName, "rwd");
                    raFile.seek(starPotion);//从starPotion位置开始写
                    int leng = 0;
                    byte[] bt = new byte[1024];
                    while ((leng = is.read(bt)) != -1) {
                        loadSize = loadSize + leng;
                        raFile.write(bt, 0, leng);
                        if(listener!=null){
                            listener.loading(fileSize, loadSize);
                        }
                        Log.e("线程" + threadId, "已下载" + loadSize);
                    }
                    Log.e("线程" + threadId, "完成" + code);
                    cunont0 = cunont0 + 1;
                    if (cunont0 == cunont) {//已下载完成
                        cunont0 = 0;
                        if(listener!=null){
                            listener.sucee(true, fileName);
                        }
                    }
                    //关闭资源
                    is.close();
                    raFile.close();
                } else {
                    Log.e("线程" + threadId, "erroCode" + code);
                    if(listener!=null){
                        listener.erro(code);
                        listener.sucee(false, fileName);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String getSDPath(Context context) {
        PermissionUtils.isStorageWritePermission(context);
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
        if (sdCardExist) {     //如果SD卡存在，则获取跟目录
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();

    }

    Listener listener;

    public interface Listener {
        void sucee(boolean isSuceess, String filePath);

        void erro(int ERRO_CODE);

        void loading(int fileSize, int loadSize);
    }

    public void setLisetner(Listener listener) {
        this.listener = listener;
    }

    /**
     * 用文件保存当前的经度
     */
    private void saveData(String fileName, String name, String valuse) {
        SharedPreferences sp = BaseApplication.getInstace().getSharedPreferences(Globals.APP_PACKAGE, Context.MODE_PRIVATE);
        SharedPreferences.Editor ed = sp.edit();
        ed.putString(fileName + "_" + name, valuse);
        ed.commit();

    }
}
